package com.company.thread;

/**
 * @description: some desc
 * @author: ruoan
 * @date: 2020/10/23 16:50
 */
public class Thread13 {


    public static void main(String[] args) {
        Object lock = new Object();
        class RunnableDemo2 implements Runnable{
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 0; i < 100; i++) {
                        System.out.println(Thread.currentThread().getName()+": 当前i的值为："+i);
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (i % 50 == 0) {
                            lock.notify(); //当线程1或2逢50的倍数，就把主线程唤起，所以当线程1或2执行完syschronized{}代码后，主线程不至于无法退出
                        }
                    }
                }

            }
        }
        Thread t = new Thread(new RunnableDemo2());
        Thread t2 = new Thread(new RunnableDemo2());
        t.setName("线程1");
        t2.setName("线程2");
        t.start();
        t2.start();
        synchronized (lock) {
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName()+": 当前i的值为："+i);
                try {
                     Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //当主线程遍历到i=50的时候，让其他的线程开始获得遍历机会
                if (i == 50) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }



    }
}



